/*
Copyright (c) 2008, Oleg S. Estekhin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package ebml.viewer;

import java.io.File;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;

import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;

import ebml.ElementDescriptor;
import ebml.ElementType;
import ebml.ElementTypes;
import ebml.VInteger;
import ebml.viewer.tree.ExtendedTreeNode;
import ebml.viewer.tree.FormatTreeNode;
import ebml.viewer.tree.NodeIcons;
import ebml.viewer.tree.StringTreeNode;

/** Creates a tree that contains EBML type inspections. */
public final class InspectionsTreeModelProvider implements FileTaskListener {

    private static final ResourceBundle RESOURCES = ResourceBundle.getBundle(Resources.class.getName());


    private final DefaultTreeModel treeModel;


    private final FormatTreeNode elementSizeInefficientEncodingAffected;

    private final FormatTreeNode elementSizeInefficientEncodingSize;


    private final FormatTreeNode signedIntegerInefficientEncodingAffected;

    private final FormatTreeNode signedIntegerInefficientEncodingSize;


    private final FormatTreeNode unsignedIntegerInefficientEncodingAffected;

    private final FormatTreeNode unsignedIntegerInefficientEncodingSize;

    private final FormatTreeNode unsignedIntegerSignedEncodingUnaffected;

    private final FormatTreeNode unsignedIntegerSignedEncodingAffected;

    private final FormatTreeNode unsignedIntegerSignedEncodingSize;


    private final FormatTreeNode asciiStringUnicodeEncodingUnaffected;

    private final FormatTreeNode asciiStringUnicodeEncodingAffected;

    private final FormatTreeNode asciiStringUnicodeEncodingSize;


    private final FormatTreeNode unicodeStringUnicodeEncodingUnaffected;

    private final FormatTreeNode unicodeStringUnicodeEncodingAffected;

    private final FormatTreeNode unicodeStringUnicodeEncodingSize;


    private final FormatTreeNode dateSecondsSignedEncodingPrecision;

    private final FormatTreeNode dateSecondsSignedEncodingEBMLEpoch;

    private final FormatTreeNode dateSecondsSignedEncodingUnixEpoch;


    /** Creates a new <code>TypeInspectionsTreeModelProvider</code> object. */
    public InspectionsTreeModelProvider() {
        ExtendedTreeNode root = new StringTreeNode(null, RESOURCES.getString("tree.inspections.root"));

        MessageFormat unaffectedInstancesFormat = new MessageFormat(RESOURCES.getString("tree.inspections.unaffectedInstances"));
        MessageFormat affectedInstancesFormat = new MessageFormat(RESOURCES.getString("tree.inspections.affectedInstances"));
        MessageFormat mostEfficientEncodingSizeFormat = new MessageFormat(RESOURCES.getString("tree.inspections.mostEfficientEncodingSize"));
        MessageFormat signedIntegerEncodingSizeFormat = new MessageFormat(RESOURCES.getString("tree.inspections.signedIntegerEncodingSize"));
        MessageFormat utfEncodingSizeFormat = new MessageFormat(RESOURCES.getString("tree.inspections.utf8nfcEncodingSize"));

        ExtendedTreeNode elementSizeNode = new StringTreeNode(null, RESOURCES.getString("tree.inspections.elementSize"));
        ExtendedTreeNode elementSizeInefficientEncoding = new StringTreeNode(null, RESOURCES.getString("tree.inspections.inefficientEncoding"));
        elementSizeInefficientEncodingAffected = new FormatTreeNode(null, affectedInstancesFormat, new Number[] {0});
        elementSizeInefficientEncodingSize = new FormatTreeNode(null, mostEfficientEncodingSizeFormat, new Number[] {0});
        elementSizeInefficientEncoding.setChildren(new TreeNode[] {elementSizeInefficientEncodingAffected, elementSizeInefficientEncodingSize});
        elementSizeNode.setChildren(new TreeNode[] {elementSizeInefficientEncoding});

        ExtendedTreeNode signedIntegerNode = new StringTreeNode(NodeIcons.SIGNED_INTEGER_ICON, ElementType.SIGNED_INTEGER.toString());
        ExtendedTreeNode signedIntegerInefficientEncoding = new StringTreeNode(null, RESOURCES.getString("tree.inspections.inefficientEncoding"));
        signedIntegerInefficientEncodingAffected = new FormatTreeNode(null, affectedInstancesFormat, new Number[] {0});
        signedIntegerInefficientEncodingSize = new FormatTreeNode(null, mostEfficientEncodingSizeFormat, new Number[] {0});
        signedIntegerInefficientEncoding.setChildren(new TreeNode[] {signedIntegerInefficientEncodingAffected, signedIntegerInefficientEncodingSize});
        signedIntegerNode.setChildren(new TreeNode[] {signedIntegerInefficientEncoding});

        ExtendedTreeNode unsignedIntegerNode = new StringTreeNode(NodeIcons.UNSIGNED_INTEGER_ICON, ElementType.UNSIGNED_INTEGER.toString());
        ExtendedTreeNode unsignedIntegerInefficientEncoding = new StringTreeNode(null, RESOURCES.getString("tree.inspections.inefficientEncoding"));
        unsignedIntegerInefficientEncodingAffected = new FormatTreeNode(null, affectedInstancesFormat, new Number[] {0});
        unsignedIntegerInefficientEncodingSize = new FormatTreeNode(null, mostEfficientEncodingSizeFormat, new Number[] {0});
        unsignedIntegerInefficientEncoding.setChildren(new TreeNode[] {unsignedIntegerInefficientEncodingAffected, unsignedIntegerInefficientEncodingSize});
        ExtendedTreeNode unsignedIntegerSignedEncoding = new StringTreeNode(null, RESOURCES.getString("tree.inspections.signedIntegerEncoding"));
        unsignedIntegerSignedEncodingUnaffected = new FormatTreeNode(null, unaffectedInstancesFormat, new Number[] {0});
        unsignedIntegerSignedEncodingAffected = new FormatTreeNode(null, affectedInstancesFormat, new Number[] {0});
        unsignedIntegerSignedEncodingSize = new FormatTreeNode(null, signedIntegerEncodingSizeFormat, new Number[] {0});
        unsignedIntegerSignedEncoding.setChildren(new TreeNode[] {unsignedIntegerSignedEncodingUnaffected, unsignedIntegerSignedEncodingAffected, unsignedIntegerSignedEncodingSize});
        unsignedIntegerNode.setChildren(new TreeNode[] {unsignedIntegerInefficientEncoding, unsignedIntegerSignedEncoding});

        ExtendedTreeNode asciiStringNode = new StringTreeNode(NodeIcons.STRING_ICON, ElementType.ASCII_STRING.toString());
        ExtendedTreeNode asciiStringUnicodeEncoding = new StringTreeNode(null, RESOURCES.getString("tree.inspections.utf8nfcEncoding"));
        asciiStringUnicodeEncodingUnaffected = new FormatTreeNode(null, unaffectedInstancesFormat, new Number[] {0});
        asciiStringUnicodeEncodingAffected = new FormatTreeNode(null, affectedInstancesFormat, new Number[] {0});
        asciiStringUnicodeEncodingSize = new FormatTreeNode(null, utfEncodingSizeFormat, new Number[] {0});
        asciiStringUnicodeEncoding.setChildren(new TreeNode[] {asciiStringUnicodeEncodingUnaffected, asciiStringUnicodeEncodingAffected, asciiStringUnicodeEncodingSize});
        asciiStringNode.setChildren(new TreeNode[] {asciiStringUnicodeEncoding});

        ExtendedTreeNode unicodeStringNode = new StringTreeNode(NodeIcons.STRING_ICON, ElementType.UTF_8_STRING.toString());
        ExtendedTreeNode unicodeStringUnicodeEncoding = new StringTreeNode(null, RESOURCES.getString("tree.inspections.utf8nfcEncoding"));
        unicodeStringUnicodeEncodingUnaffected = new FormatTreeNode(null, unaffectedInstancesFormat, new Number[] {0});
        unicodeStringUnicodeEncodingAffected = new FormatTreeNode(null, affectedInstancesFormat, new Number[] {0});
        unicodeStringUnicodeEncodingSize = new FormatTreeNode(null, utfEncodingSizeFormat, new Number[] {0});
        unicodeStringUnicodeEncoding.setChildren(new TreeNode[] {unicodeStringUnicodeEncodingUnaffected, unicodeStringUnicodeEncodingAffected, unicodeStringUnicodeEncodingSize});
        unicodeStringNode.setChildren(new TreeNode[] {unicodeStringUnicodeEncoding});

        ExtendedTreeNode dateNode = new StringTreeNode(null, ElementType.DATE.toString());
        ExtendedTreeNode dateSignedEncoding = new StringTreeNode(null, RESOURCES.getString("tree.inspections.signedIntegerEncoding"));
        dateSecondsSignedEncodingPrecision = new FormatTreeNode(null, new MessageFormat(RESOURCES.getString("tree.inspections.dateToSecondsPrecisionLoss")), new Number[] {0});
        dateSecondsSignedEncodingEBMLEpoch = new FormatTreeNode(null, new MessageFormat(RESOURCES.getString("tree.inspections.dateToSecondsEBML")), new Number[] {0});
        dateSecondsSignedEncodingUnixEpoch = new FormatTreeNode(null, new MessageFormat(RESOURCES.getString("tree.inspections.dateToSecondsUnix")), new Number[] {0});
        dateSignedEncoding.setChildren(new TreeNode[] {dateSecondsSignedEncodingPrecision, dateSecondsSignedEncodingEBMLEpoch, dateSecondsSignedEncodingUnixEpoch});
        dateNode.setChildren(new TreeNode[] {dateSignedEncoding});

        root.setChildren(new TreeNode[] {elementSizeNode, signedIntegerNode, unsignedIntegerNode, asciiStringNode, unicodeStringNode, dateNode});
        treeModel = new DefaultTreeModel(root, true);
    }


    private void updateMessageArgument(FormatTreeNode node, int delta) {
        Number[] arguments = (Number[]) node.getMessageArguments();
        arguments[0] = arguments[0].intValue() + delta;
        nodeChanged(node);
    }

    private void updateMessageArgument(FormatTreeNode node, long delta) {
        Number[] arguments = (Number[]) node.getMessageArguments();
        arguments[0] = arguments[0].longValue() + delta;
        nodeChanged(node);
    }


    private void inspectElementSize(VInteger size) {
        VInteger v = VInteger.encode(size.getValue());
        if (v.getEncodedSize() < size.getEncodedSize()) {
            updateMessageArgument(elementSizeInefficientEncodingAffected, 1);
            updateMessageArgument(elementSizeInefficientEncodingSize, v.getEncodedSize() - size.getEncodedSize());
        }
    }


    /**
     * Returns the <code>TreeModel</code> constructed by this provider.
     *
     * @return the tree model
     */
    public TreeModel getTreeModel() {
        return treeModel;
    }


    @Override
    public void startFile(File file, long size) {
    }

    @Override
    public void signedIntegerElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        inspectElementSize(size);
        // inefficient encoding
        long minimumSize = ElementTypes.getMinimumSignedIntegerEncodedSize(value);
        if (minimumSize < size.getValue()) {
            updateMessageArgument(signedIntegerInefficientEncodingAffected, 1);
            updateMessageArgument(signedIntegerInefficientEncodingSize, minimumSize - size.getValue());
        }
    }

    @Override
    public void unsignedIntegerElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        inspectElementSize(size);
        // inefficient encoding
        long minimumSize = ElementTypes.getMinimumUnsignedIntegerEncodedSize(value);
        if (minimumSize < size.getValue()) {
            updateMessageArgument(unsignedIntegerInefficientEncodingAffected, 1);
            updateMessageArgument(unsignedIntegerInefficientEncodingSize, minimumSize - size.getValue());
        }
        // encoded as a signed integer
        long signedMinimumSize = ElementTypes.getMinimumSignedIntegerEncodedSize(value);
        if (minimumSize >= signedMinimumSize) {
            updateMessageArgument(unsignedIntegerSignedEncodingUnaffected, 1);
        } else {
            updateMessageArgument(unsignedIntegerSignedEncodingAffected, 1);
            updateMessageArgument(unsignedIntegerSignedEncodingSize, signedMinimumSize - minimumSize);
        }
    }

    @Override
    public void floatElement(long position, ElementDescriptor descriptor, VInteger size, Number value) {
        inspectElementSize(size);
    }

    @Override
    public void asciiStringElement(long position, ElementDescriptor descriptor, VInteger size, String value) {
        inspectElementSize(size);
        // encoded as an UTF-8 NFC
        long utf8Size = ElementTypes.getMinimumUTF8StringEncodedSize(value);
        if (utf8Size == size.getValue()) {
            updateMessageArgument(asciiStringUnicodeEncodingUnaffected, 1);
        } else {
            updateMessageArgument(asciiStringUnicodeEncodingAffected, 1);
            updateMessageArgument(asciiStringUnicodeEncodingSize, utf8Size - size.getValue());
        }
    }

    @Override
    public void unicodeStringElement(long position, ElementDescriptor descriptor, VInteger size, String value) {
        inspectElementSize(size);
        // encoded as an UTF-8 NFC
        long utf8Size = ElementTypes.getMinimumUTF8StringEncodedSize(value);
        if (utf8Size == size.getValue()) {
            updateMessageArgument(unicodeStringUnicodeEncodingUnaffected, 1);
        } else {
            updateMessageArgument(unicodeStringUnicodeEncodingAffected, 1);
            updateMessageArgument(unicodeStringUnicodeEncodingSize, utf8Size - size.getValue());
        }
    }

    @Override
    public void dateElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        inspectElementSize(size);
        // encoded as a signed integer
        long seconds = TimeUnit.NANOSECONDS.toSeconds(value);
        long nano = TimeUnit.SECONDS.toNanos(seconds);
        if (nano != value) {
            updateMessageArgument(dateSecondsSignedEncodingPrecision, Math.abs(nano - value));
        }
        long ebmlSize = ElementTypes.getMinimumSignedIntegerEncodedSize(seconds);
        updateMessageArgument(dateSecondsSignedEncodingEBMLEpoch, ebmlSize - size.getValue());
        long unixSize = ElementTypes.getMinimumSignedIntegerEncodedSize(seconds + 978307200L);
        updateMessageArgument(dateSecondsSignedEncodingUnixEpoch, unixSize - size.getValue());
    }

    @Override
    public void binaryElement(long position, ElementDescriptor descriptor, VInteger size) {
        inspectElementSize(size);
    }

    @Override
    public void startContainer(long position, ElementDescriptor descriptor, VInteger size) {
        inspectElementSize(size);
    }

    @Override
    public void endContainer(long position, ElementDescriptor descriptor) {
    }

    @Override
    public void unknownElement(long position, VInteger identifier, VInteger size) {
        inspectElementSize(size);
    }

    @Override
    public void endFile() {
    }

    @Override
    public void error(Throwable e) {
    }

    @Override
    public void fatalError(Throwable e) {
    }


    private void nodeChanged(final TreeNode treeNode) {
        if (SwingUtilities.isEventDispatchThread()) {
            nodeChangedUnsafe(treeNode);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    nodeChangedUnsafe(treeNode);
                }
            });
        }
    }

    private void nodeChangedUnsafe(TreeNode treeNode) {
        treeModel.nodeChanged(treeNode);
    }

}
